# day04/conftest.py
import pytest
import os
import sys
import logging  # 添加这行导入
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

@pytest.fixture(scope="function")
def browser():
    chrome_options = Options()
    unique_data_dir = os.path.join(os.path.dirname(__file__), 'chrome_data')
    os.makedirs(unique_data_dir, exist_ok=True)
    chrome_options.add_argument(f"--user-data-dir={unique_data_dir}")
    chrome_options.add_argument("--start-maximized")
    chrome_options.add_argument("--disable-blink-features=AutomationControlled")
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_argument(
        "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

    driver = webdriver.Chrome(options=chrome_options)
    driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
    driver.implicitly_wait(3)

    # 启动时检查是否已登录
    driver.get("https://www.bilibili.com")
    try:
        avatar_xpath = '//*[@id="i_cecream"]/div[2]/div[1]/div[1]/ul[2]/li[1]/div[1]/a[1]/picture/img'
        WebDriverWait(driver, 4).until(
            EC.presence_of_element_located((By.XPATH, avatar_xpath))
        )
        logger.info("检测到已登录状态（头像元素存在）")
    except TimeoutException:
        pytest.fail("未检测到登录状态（未找到用户头像元素）")

    yield driver
    driver.quit()